/**
 * @description 脚手架启动阶段 封装init package功能
 */
"use strict";

const pakDir = require("pkg-dir").sync; //获取路径下的package路径
const path = require("path");
const npminstall = require("npminstall"); //下载package工具
const fse = require("fs-extra"); //处理文件
const pathExists = require("path-exists").sync;
const formatPath = require("@spiritos-cli/format-path");
const {
  getDefaultRegistry,
  getNpmLatestVersion,
} = require("@spiritos-cli/get-npm-info");
const { isObject } = require("@spiritos-cli/utils");

class Package {
  constructor(options) {
    if (!options || !isObject(options)) {
      throw new Error("Package类的options参数不能为空");
    }
    //package的路径
    this.targetPath = options.targetPath;
    //package的缓存路径
    this.storeDir = options.storeDir;
    //pageage name
    this.packageName = options.packageName;
    //package的version
    this.packageVersion = options.packageVersion;
    this.cacheFilePathPrefix = this.packageName.replace("/", "_");
  }

  /**
   * 将lastversion转化成版本号
   */
  async prepare() {
    if (this.storeDir && pathExists(this.storeDir)) {
      fse.mkdirpSync(this.storeDir);
    }
    if (this.packageVersion === "latest") {
      this.packageVersion = await getNpmLatestVersion(this.packageName);
    }
  }

  /**
   * 更新的路径转换
   */
  get cacheFilePath() {
    return path.resolve(this.storeDir, `_${this.cacheFilePathPrefix}@${this.packageVersion}@${this.packageName}`);
  }

  /**
   * 获取最新版本号安装包时候的路径
   * @param {string} packageVersion
   */
  getSpaceificcacheFilePath(packageVersion) {
    return path.resolve(
      this.storeDir,
      `_${this.cacheFilePathPrefix}@${packageVersion}@${this.packageName}`
    );
  }

  /**
   * 判断当前Package是否存在
   */
  async exists() {
    if (this.storeDir) {
      await this.prepare();
      return pathExists(this.cacheFilePath);
      //缓存模式
    } else {
      return pathExists(this.targetPath);
    }
  }

  /**
   * 安装package
   */
  async install() {
    await this.prepare();
    return npminstall({
      root: this.targetPath, //目标地址
      storeDir: this.storeDir, //缓存地址
      registry: getDefaultRegistry(), //下载源
      pkgs: [
        //包的信息
        {
          name: this.packageName, //名称
          version: this.packageVersion, //版本号
        },
      ],
    });
  }

  /**
   * 更新package
   */
  async update() {
    await this.prepare();
    //1.获取最新的npm版本号
    const latestPackageVersion = await getNpmLatestVersion(this.packageName);
    //2.查询最新版本号对应的路径是否存在
    const latestFilePath = this.getSpaceificcacheFilePath(latestPackageVersion);
    //3.如果不存在，则直接安装最新版本
    if (!pathExists(latestFilePath)) {
      await npminstall({
        root: this.targetPath, //目标地址
        storeDir: this.storeDir, //缓存地址
        registry: getDefaultRegistry(), //下载源
        pkgs: [
          //包的信息
          {
            name: this.packageName, //名称
            version: latestPackageVersion, //版本号
          },
        ],
      });
      this.packageVersion = latestPackageVersion;
    }else{
      this.packageVersion = latestPackageVersion;
    }
   
    return latestFilePath;
  }

  /**
   * 获取入口文件的路径
   */
  getRootFilePatn() {
    function _getRootFile(targetPath) {
      const dir = pakDir(targetPath);
      if (dir) {
        //2.读取 package.json
        const pkgFile = require(path.resolve(dir, "package.json"));
        //3.寻找main/lib
        if (pkgFile && pkgFile.main) {
          //4.路径兼容（macOs/wind)
          return formatPath(path.resolve(dir, pkgFile.main));
        }
      }
      return null;
    }
    //1.获取package.json 所在目录 - pkg-dir
    if (this.storeDir) {
    return _getRootFile(this.cacheFilePath);
    } else {
      return _getRootFile(this.targetPath);
    }
  }
}
module.exports = Package;
